var crypto = require('../utils/crypto');
var express = require('express');
var db = require('../utils/db');
var http = require('../utils/http');
var help = require('../utils/help');

var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
  extended: true
}));
app.set('jwtTokenSecret', 'gy_liliang_waibao');
var hallAddr = '';

var kaijiangTimes = 0;

var lottyProductOrder = [];
var lastnumber = 0;
var lottyOpentime;
var oneSecond = 60 * 1000;
var message = '';

var beilvone = 5;
var beilvtwo = 1.9;

function send(res, ret) {
  var str = JSON.stringify(ret);
  res.send(str);
}

var config = null;
// 创建 application/x-www-form-urlencoded 编码解析

exports.start = function (cfg) {
  config = cfg;
  hallAddr = config.HALL_IP + ':' + config.HALL_CLIENT_PORT;
  app.listen(config.CLIENT_PORT);
  console.log('account server is listening on ' + config.CLIENT_PORT);
};

// 设置跨域访问
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With');
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  res.header('X-Powered-By', ' 3.2.1');
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
});
app.post('/process_post', function (req, res, next) {
  // 输出 JSON 格式
  var response = {
    first_name: req.body.mobile,
    last_name: req.body.password
  };
  console.log(response);
  res.end(JSON.stringify(response));
});

app.post('/account/login', function (req, res, next) {
  var opneid = crypto.md5(req.body.opneid);
  var userinfo = req.body.userinfo;
  var fnFailed = function () {
    send(res, { errcode: 1, errmsg: 'account has been used.' });
  };

  var fnSucceed = function (tplayerid) {
    send(res, { errcode: 0, errmsg: 'ok', playerid: tplayerid });
  };
  // console.log('/register' + account + 'password' + password);
  db.is_account_exist(opneid, function (exist) {
    if (!exist) {
      console.log('create user.');
      db.create_account(opneid, function (ret) {
        if (ret) {
          console.log('sucess.');
          db.get_player_id(opneid, function (ret) {
            if (ret == null) {
              console.log('sucess.');
              fnSucceed(ret);
            } else {
              console.log('fail');
              fnFailed();
            }
          });
        } else {
          console.log('fail');
          fnFailed();
        }
      });
    } else {

      db.get_player_id(opneid, function (ret) {
        if (ret != null) {
          console.log('sucess.');
          fnSucceed(ret);
        } else {
          console.log('fail');
          fnFailed();
        }
      });
      console.log('account has been used.');
    }
  });

});

//  POST 请求
app.post('/', function (req, res, next) {
  console.log('主页 POST 请求');
  res.send('Hello POST');
});


app.get('/get_version', function (req, res) {
  var ret = {
    version: config.VERSION
  };
  send(res, ret);
});

app.get('/get_serverinfo', function (req, res) {
  console.log('get_serverinfo been used.');
  var ret = {
    version: config.VERSION,
    hall: hallAddr,
    appweb: config.APP_WEB
  };
  send(res, ret);
});



var appInfo = {
  Android: {
    appid: 'wxe39f08522d35c80c',
    secret: 'fa88e3a3ca5a11b06499902cea4b9c01'
  },
  iOS: {
    appid: 'wxcb508816c5c4e2a4',
    secret: '7de38489ede63089269e3410d5905038'
  }
};


//获取玩家的OPENID
function get_access_openid(topneid, tuserinfo, res, callback) {
  //var info = appInfo[os];
  //if (info == null) {
  //  callback(false, null);
  //}
  /*var data = {
    appid: info.appid,
    secret: info.secret,
    code: code,
    grant_type: 'authorization_code'
  };
  
  http.get2('https://api.weixin.qq.com/sns/oauth2/access_token', data, callback, true);*/
  //var opneid = crypto.md5( req.body.opneid);
  //var userinfo = req.body.userinfo;
  var info = topneid;

  var ttuserinfo = JSON.parse(tuserinfo);
  var ret = {
    openid: info,
    userinfo: tuserinfo,
    nickname: ttuserinfo.nickName,
    sex: ttuserinfo.gender,
    headimgurl: ttuserinfo.avatarUrl,
  };
  callback(true, ret, res);
  return;

}

function getAccountId(openid, callback) {
  db.get_user_accoountid(openid, callback);
}

function create_user(account, name, sex, headimgurl, callback) {
  var coins = 1000;
  var gems = 21;
  db.is_user_exist(account, function (ret) {
    if (!ret) {
      db.create_user(account, name, sex, headimgurl, coins, gems, function (ret) {


        callback();
      });
    } else {
      db.update_user_info(account, name, headimgurl, sex, function (ret) {
        callback();
      });
    }
  });
}



app.post('/wechat/auth', function (req, res, next) {
  var opneid = crypto.md5(req.body.opneid);
  var userinfo = req.body.userinfo;
  if (userinfo == null || userinfo == '' || opneid == null || opneid == '') {
    return;
  }
  console.log(userinfo);
  get_access_openid(opneid, userinfo, res, function (suc, data, res) {
    if (suc) {

      var openid = data.openid;
      var nickname = data.nickname;
      var sex = data.sex;
      var headimgurl = data.headimgurl;
      var account = openid;
      create_user(account, nickname, sex, headimgurl, function () {
        getAccountId(opneid, function (tdata) {
          if (tdata != null) {
           
            var sign = crypto.md5(tdata + config.ACCOUNT_PRI_KEY);
 
            var ret = {
              errcode: 0,
              errmsg: 'ok',
              account: tdata,
              halladdr: hallAddr,
              sign: sign
            };
            send(res, ret);
          }
        });

      });





    } else {
      send(res, { errcode: -1, errmsg: 'unkown err.' });
    }
  });
});

app.get('/base_info', function (req, res) {
  var userid = req.query.userid;
  db.get_user_base_info(userid, function (data) {
    var ret = {
      errcode: 0,
      errmsg: 'ok',
      name: data.name,
      sex: data.sex,
      headimgurl: data.headimg
    };
    send(res, ret);
  });
});

